import math
from datetime import datetime

import okx.MarketData as MarketData
import peewee

from config.base_config import *
from okex.okex_k_line_model import create_k_line_model
from utils.date_util import split_day

flag = "0"  # 实盘:0 , 模拟盘：1
marketDataAPI = MarketData.MarketAPI(flag=flag)


def okex_download_k_line(inst_id, begin, end, bar):
    '''
    下载k线数据
    :param inst_id: 产品
    :param begin: 开始时间
    :param end: 结束时间
    :param bar: 时间粒度，默认值1m 如 [1s/1m/3m/5m/15m/30m/1H/2H/4H]
    :return:
    '''
    logging.info(f"开始获取数据，时间为：{begin}")
    bar_name = ''
    time_name = ''
    begin_time = datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    n = 0  # 时间个数，通过开始时间和结束时间进行计算
    if bar == '1s':
        bar_name = 'one_second'
        time_name = '%Y-%m-%d-%H'
        # 计算秒钟差
        n = (end_time - begin).total_seconds()
    elif bar == '1m':
        bar_name = 'one_minute'
        time_name = '%Y-%m'
        # 计算分钟差并向下取整
        n = math.floor((end_time - begin).total_seconds() / 60)
    elif bar == '1h':
        bar_name = 'one_hour'
        time_name = '%Y'
        # 计算小时差并向下取整
        n = math.floor((end_time - begin).total_seconds() / 3600)
    k_line_name = 'k_line_' + bar_name + '_' + (datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")).strftime(
        time_name)
    # 创建表和模型，1s按天创建，1m按月创建，1h按年创建
    KLine = create_k_line_model(k_line_name)

    print(KLine)


def okex_download_k_line_one_seconds(inst_id, begin, end):
    begin_time = datetime.strptime(begin, "%Y-%m-%d %H:%M:%S")
    end_time = datetime.strptime(end, "%Y-%m-%d %H:%M:%S")
    date_ranges = split_day(begin_time, end_time)
    for start, end in date_ranges:
        print(f"开始时间: {start}, 结束时间: {end}")
        print(start)
        k_line_name = 'k_line_one_second_' + start.strftime('%Y-%m-%d')
        KLine = create_k_line_model(k_line_name)
        # 转换为毫秒级别的时间戳
        begin_milliseconds = int(start.timestamp() * 1000)
        # 计算秒钟差
        n = int((end - start).total_seconds())
        for i in range(0, n, 100):
            before = i * 1000 + begin_milliseconds
            after = (i + 101) * 1000 + begin_milliseconds
            print(before)
            print(after)
            result = marketDataAPI.get_history_candlesticks(
                instId=inst_id,
                bar='1s',
                before=before,
                after=after
            )
            data = result['data']
            # 插入数据
            for record in reversed(data):
                create_time = datetime.fromtimestamp(float(record[0]) / 1000.0)
                try:
                    KLine.create(
                        plat='okex',
                        inst_id=inst_id,
                        ts=record[0],
                        o=record[1],
                        h=record[2],
                        l=record[3],
                        c=record[4],
                        create_time=create_time
                    )
                except peewee.IntegrityError:
                    print("主键重复")
